package main

import (
	"bufio"
	"bytes"
	"crypto/sha256"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"sort"
	"strconv"
	"strings"
	"time"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	for true {
		// 请求接口获取实时胜率数据
		fmt.Print("请输入需要查询实时胜率的和平精英实时比赛id（输入'exit'退出）：")
		gpLiveMatchId, _ := reader.ReadString('\n')
		gpLiveMatchId = strings.TrimSpace(gpLiveMatchId)
		fmt.Println("")
		if gpLiveMatchId == "exit" {
			break
		}

		fmt.Print("请输入需要查询实时胜率的时间秒数（输入'exit'退出）：")
		gpLiveMatchTime, _ := reader.ReadString('\n')
		gpLiveMatchTime = strings.TrimSpace(gpLiveMatchTime)
		fmt.Println("")
		fmt.Println("查询中请稍后。。。～（￣▽￣～）（～￣▽￣）～。")
		fmt.Println("")
		doSearch(gpLiveMatchId, gpLiveMatchTime)
		fmt.Println("")
		fmt.Println("查询完成！（o゜▽゜）o☆[BINGO！]")
		fmt.Println("")
	}
}

func doSearch(gpLiveMatchId string, gpLiveMatchTime string) {
	playTime := gpLiveMatchTime
	params := map[string]string{
		"battleid": gpLiveMatchId,
		"playTime": playTime,
		"method":   "1",
	}

	// 时间戳
	timeStamp := fmt.Sprintf("%d", time.Now().Unix())
	secret := "gz@skynet2022x8"
	appId := "idata22x8"

	// 排序参数
	keys := make([]string, 0, len(params))
	for k := range params {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	// 构建待签名的字符串
	var paramStr string
	for _, k := range keys {
		paramStr += k + "=" + params[k] + "&"
	}
	paramStr = paramStr[:len(paramStr)-1]

	// 构建签名
	signature := fmt.Sprintf("%X", sha256.Sum256([]byte(timeStamp+secret+paramStr+timeStamp)))

	// 构建请求
	url := fmt.Sprintf("https://momi.qq.com/api/pub_api.access?api=idata22.predict&app=%s", appId)
	reqBody, _ := json.Marshal(map[string]map[string]string{
		"params": params,
	}) // 将参数转换为 JSON 字符串

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(reqBody))
	if err != nil {
		fmt.Println(err)
		return
	}

	req.Header.Set("TIMESTAMP", timeStamp)
	req.Header.Set("SIGNATURE", signature)
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()

	// 读取响应
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(err)
		return
	}
	if resp.StatusCode == http.StatusOK {
		unquoted, err := strconv.Unquote(string(body))
		if err != nil {
			fmt.Println(err)
			return
		}

		var prettyJSON bytes.Buffer
		err = json.Indent(&prettyJSON, []byte(unquoted), "", "  ")
		if err != nil {
			fmt.Println(err)
			return
		}

		fmt.Println("和平精英实时胜率查询结果：", string(prettyJSON.Bytes()))
	} else {
		fmt.Println("HTTP请求失败：", resp.Status)
	}
}
